package com.itheima.shorturl.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;


import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

/**
 * @author andy
 * @date 21/4/21
 * @description Ip Utils 获取IP 判断IP是否在内网
 * @version 1.0
 */

@Slf4j
public class IpUtils {
    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP1 = "127.0.0.1";
    private static final String LOCALHOST_IP2 = "::1";
    private static final String LOCALHOST_IP3 = "localhost";

    /**
     * 获取IP地址
     * <p>
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
            ip = request.getHeader("X-Original-Forwarded-For");
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }
            //获取nginx等代理的ip
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("x-forwarded-for");
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            //兼容k8s集群获取ip
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (LOCALHOST_IP.equalsIgnoreCase(ip)
                        || LOCALHOST_IP1.equalsIgnoreCase(ip)
                        || LOCALHOST_IP2.equalsIgnoreCase(ip)
                        || LOCALHOST_IP3.equalsIgnoreCase(ip)) {
                    //根据网卡取本机配置的IP
                    InetAddress iNet;
                    try {
                        iNet = InetAddress.getLocalHost();
                        ip = iNet.getHostAddress();
                    } catch (UnknownHostException e) {
                        log.error("getClientIp error: ", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("IPUtils ERROR ", e);
        }
        //使用代理，则获取第一个IP地址
        if (!StringUtils.isBlank(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }

        return StringUtils.isBlank(ip) ? LOCALHOST_IP1 : ip;
    }


    /*
     * 10.x.x.x/8
     */

    private static final byte SECTION_1 = 0x0A;

    /*
     * 172.16.x.x/12
     */

    private static final byte SECTION_2 = (byte) 0xAC;
    private static final byte SECTION_3 = (byte) 0x10;
    private static final byte SECTION_4 = (byte) 0x1F;

    /*
    192.168.x.x/16
     */

    private static final byte SECTION_5 = (byte) 0xC0;
    private static final byte SECTION_6 = (byte) 0xA8;

    private static final List<String> LOCAL_LIST = Arrays.asList(LOCALHOST_IP, LOCALHOST_IP1, LOCALHOST_IP2, LOCALHOST_IP3);
    /**
     * 内网IP段范围
     * 10.0.0.0/8：10.0.0.0～10.255.255.255
     * 172.16.0.0/12：172.16.0.0～172.31.255.255
     * 192.168.0.0/16：192.168.0.0～192.168.255.255
     * 本机
     * 127.0.0.1 localhost ::1 0:0:0:0:0:0:0:1
     * can use code segment for test:
     * ************
     * public static void main(String[] args) {
     *         System.out.println(inLocalAreaNetwork("10.0.0.0"));
     *         System.out.println(inLocalAreaNetwork("10.1.0.0"));
     *         System.out.println(inLocalAreaNetwork("10.0.2.0"));
     *         System.out.println(inLocalAreaNetwork("172.16.0.0"));
     *         System.out.println(inLocalAreaNetwork("172.31.255.255"));
     *         System.out.println(inLocalAreaNetwork("172.22.255.255"));
     *         System.out.println(inLocalAreaNetwork("192.168.0.0"));
     *         System.out.println(inLocalAreaNetwork("192.168.0.1"));
     *         System.out.println(inLocalAreaNetwork("192.168.0.255"));
     *         System.out.println(inLocalAreaNetwork("193.168.0.255"));
     *     }
     * *************
     * @param ip ip
     * @return in LAN true, or false
     */
    public static boolean inLocalAreaNetwork(String ip){
        if (LOCAL_LIST.contains(ip)){
            return true;
        }

        byte[] addr = IPAddressUtil.textToNumericFormatV4(ip);
        final byte b0 = addr[0];
        final byte b1 = addr[1];

        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                if (SECTION_6 == b1){
                    return true;
                }
            default:
                return false;
        }
    }
}